/*
 * @Author: lei
 * @Description: 
 * @FilePath: /code/parallel_computation.cc
 */
#include <mutex>
#include <iostream>
#include <thread>
#include <chrono>
#include <numeric>
#include <vector>
#include <future>


std::mutex m;
struct X {
 void foo(int i, const std::string& str) {
 std::lock_guard<std::mutex> lk(m);
 std::cout << str << ' ' << i << '\n';
    }
 void bar(const std::string& str) {
 std::lock_guard<std::mutex> lk(m);
 std::cout << str << '\n';
    }
 int operator()(int i) {
 std::lock_guard<std::mutex> lk(m);
 std::cout << i << '\n';
 return i + 10;
    }
};
 
template <typename RandomIt>
int parallel_sum(RandomIt beg, RandomIt end)
{
 auto len = end - beg;
 if (len < 100000)
 return std::accumulate(beg, end, 0);
 
    RandomIt mid = beg + len/2;
 auto handle = std::async(std::launch::async,
                             parallel_sum<RandomIt>, mid, end);
 int sum = parallel_sum(beg, mid);
 return sum + handle.get();
}
 

int main()
{
 std::vector<int> v(10000000, 1);
 auto start=std::chrono::steady_clock::now();
 std::cout << "异步开线程： The sum is " << parallel_sum(v.begin(), v.end()) << '\n';//do_something() took 0.78942 seconds
 //std::cout << "同步 The sum is " << std::accumulate(v.begin(), v.end(),0) << '\n';//do_something() took 0.104976 seconds
 auto stop=std::chrono::steady_clock::now();
 
 std::cout<<"do_something() took "<<std::chrono::duration<double>(stop-start).count()<<" seconds"<<std::endl;
 //std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
}